//
//  StatusesViewModel.swift
//  WeiBo
//
//  Created by 陈贵 on 15/9/11.
//  Copyright © 2015年 hzj. All rights reserved.
//

import UIKit
import ReactiveCocoa
import SDWebImage

class StatusesListViewModel: NSObject {
    
/// 单例
//    static var sharedStatusesListViewModel = StatusesListViewModel()
    
    ///微博数据
    lazy var statusesList: [AnyObject] = [StatusesViewModel]()

    //    获取当前登录用户及其所关注用户的最新微博
    func loadTheData(isPullUpRefresh:Bool) ->RACSignal{
        //判断是否是下拉刷新
        
        var since_id:Int
        var max_id:Int
        if isPullUpRefresh {
             max_id = (statusesList.count ?? 0) == 0 ? 0 : (statusesList.last as! StatusesViewModel).statuses.id
            since_id = 0
        }else{
             since_id = (statusesList.count ?? 0) == 0 ? 0 : (statusesList.first as! StatusesViewModel).statuses.id
            max_id = 0
        }
        
        return RACSignal.createSignal({[weak self] (subscriber) -> RACDisposable! in
            NetworkTool.sharedTool.loadTheStatus(Since_id: since_id, max_id:max_id).subscribeNext({ (result) -> Void in
//                printLog(result)
                guard let statusesArray = result["statuses"] as? [[String : AnyObject]] else{
                    printLog("没有正确的数据")
                    
                    subscriber.sendError(NSError(domain: "com.hzj.error", code: -1233, userInfo: ["error meessage":"错误的数据"]))
                    return
                }
//                printLog(statusesArray)
                
                //创建临时数组，用以保存获得之数据
                var temArray = [AnyObject]()
                
                for dic in statusesArray{
                    temArray.append(StatusesViewModel(statuses:Statuses(dict: dic)))
                }
//                printLog(self.statusesList)
                
                self?.saveTheImage(temArray as! [StatusesViewModel], finished: { () -> () in

                    //将新缓存图片加入图片数组中
                    if isPullUpRefresh {
                        //下拉刷新时
                        print("向上拉")
                        self?.statusesList = self!.statusesList + temArray
                    }else{
                        print("向下拉")
                        self?.statusesList = temArray + self!.statusesList
                        subscriber.sendNext(temArray.count)
                    }
                    //放松成功信号
                    subscriber.sendCompleted()
                })
                
                }, error: { (error) -> Void in
                    printLog(error)
                }) { () -> Void in
                    printLog("成功")
            }
            return nil
        })
    }
    
    
/// 保存单张图片
    func saveTheImage(array:[StatusesViewModel],finished:()->()){
        
        var imageLength = 0
        
        //调度组
         let group = dispatch_group_create()
        
        
        for picArray in array{
            
            let count = picArray.thumbnailURLs?.count ?? 0
            if count != 1{
                //结束单次循环
                continue
            }
//            printLog(picArray.thumbnailURLs)
            
            //进组
            dispatch_group_enter(group)
            
            SDWebImageManager.sharedManager().downloadImageWithURL(picArray.thumbnailURLs![0], options: [], progress: nil, completed: { (image, _, _, _, _) in
                
                if image != nil{
                    let imageData = UIImagePNGRepresentation(image)
                    imageLength += imageData?.length ?? 0
                }
                
                //出组
                dispatch_group_leave(group)
                
            })
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            printLog("总缓存图片大小\(imageLength / 1024)k")
            //执行闭包
            finished()

        }
    }
    
}

